<template>
  <div>
    <el-card class="box-card">
      <el-form ref="selectform" :inline="true" :model="selectform" class="demo-form-inline ManagementClass">

        <el-form-item label="被叫号码">
          <el-input v-model="selectform.toPhone" size="mini" clearable placeholder="请输入被叫号码"
                    prefix-icon="el-icon-search"
                    class="AuthorityInput managementBtn"/>
        </el-form-item>

        <el-form-item label="主叫号码">
          <el-input v-model="selectform.fromPhone" size="mini" clearable placeholder="请输入主叫号码"
                    prefix-icon="el-icon-search"
                    class="AuthorityInput managementBtn"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="mini" @click="selectSubmit()">查询</el-button>
          <el-button type="info" size="mini" @click="selectResetForm('selectform')">重置</el-button>
          <el-button type="success" size="mini" @click="importCallInfoVisible = true">导入号码</el-button>
          <el-button type="warning" size="mini" @click="batchDeleteBtn()">批量删除</el-button>
          <el-button type="danger" size="mini" @click="openFileBtn(0)">配置文件</el-button>
          <el-button type="danger" style="background-color: #a509e3;border-color:#a509e3;" size="mini" @click="startCallBtn(null)">批量外呼</el-button>
          <el-button type="danger" style="background-color: blue;border-color:blue" size="mini" @click="startCallBackBtn(null)">批量回调</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card" style="margin-top: 6px">

      <el-table v-loading="loading"
                ref="multipleTable"
                :data="tableData" border size="mini" style="width: 100%"
                :header-cell-style="{ 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'center' }"
                :row-key="getRowKey"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" :reserve-selection="true" width="30">
        </el-table-column>
        <el-table-column prop="index" label="序号" width="55">
        </el-table-column>
        <el-table-column prop="toPhone" label="被叫号码" width="130">
        </el-table-column>
        <el-table-column prop="fromPhone" label="主叫号码" width="130">
        </el-table-column>
        <el-table-column prop="callPause" label="通话暂停|秒" width="100">
        </el-table-column>
        <el-table-column prop="welcomeText" label="欢迎语" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="status" label="通话状态" width="80">
        </el-table-column>
        <el-table-column prop="duration" label="外呼时长" width="80">
        </el-table-column>
        <el-table-column prop="recordLocalUrl" label="录音地址" width="80" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="callTime" label="外呼时间" width="135">
          <template slot-scope="scope">
            {{ scope.row.callbackTime == '2008-08-08 00:00:00' ? '' : scope.row.callbackTime }}
          </template>
        </el-table-column>
        <el-table-column prop="callbackTime" label="回调时间" width="135">
          <template slot-scope="scope">
            {{ scope.row.callbackTime == '2008-08-08 00:00:00' ? '' : scope.row.callbackTime }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="135">
        </el-table-column>
        <el-table-column prop="callSid" label="外呼标识" width="135" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="recordingSid" label="录音标识" width="135" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="callResponse" label="外呼响应" width="150" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="callBackResponse" label="回调响应" width="150" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="290">
          <template slot-scope="scope">
            <el-button type="success" size="mini" :disabled="scope.row.callSid !== ''" @click="startCallBtn(scope.row.id)">发起外呼</el-button>
            <el-button type="danger" size="mini" :disabled="scope.row.recordingSid !== ''" @click="startCallBackBtn(scope.row.id)">发起回调</el-button>
            <el-button type="primary" size="mini" :disabled="scope.row.recordLocalUrl == ''" @click="audioPlay(scope.row.recordLocalUrl)">播放录音</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <pagination :pager="pager" @search="search"/>

    <el-dialog title="导入号码" :visible.sync="importCallInfoVisible">

      <el-form :label-position="labelPosition" :model="importCallInfoForm" label-width="80px">
        <el-form-item label="主叫号码">
          <el-input
            placeholder="请输入主叫号码（需要带区号 参考：+12097634840）如果未输入,则取配置文件里面的"
            v-model="importCallInfoForm.fromPhone"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="欢迎语">
          <el-input type="textarea"
                    size="mini"
                    v-model="importCallInfoForm.welcomeText"
                    placeholder="请输入欢迎语-接通后自动播放的话术"></el-input>
        </el-form-item>
        <el-form-item label="通话暂停">
          <el-input-number v-model="importCallInfoForm.callPause" size="mini" :min="5" :max="180"></el-input-number>
          【播完·欢迎语·多少秒后自动挂断】
        </el-form-item>
        <el-form-item label="被叫号码">
          <el-input type="textarea"
                    v-model="importCallInfoForm.toPhoneLine"
                    :autosize="{ minRows: 5, maxRows: 10}"
                    placeholder="请输入被叫号码（需要带区号 参考：+12097634840）一行一个号码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="importCallInfoVisible = false">取 消</el-button>
          <el-button type="primary" @click="importCallInfoBtn()">确 定</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>


<style scoped>
/* 调整 el-form 的布局，使表单项左对齐 */
.el-form {
  text-align: left;
  display: block;
}

/* 使每个表单项的标签左对齐 */
.el-form-item__label {
  text-align: left !important;
  width: auto; /* 自动宽度 */
  margin-right: 5px; /* 控制标签和输入框之间的间距 */
}

/* 使表单项的输入框左对齐 */
.el-form-item__content {
  display: inline-block;
}
</style>

<script>
import {batchDelete, page , openFile} from "../../api/common";
import {importCallInfo} from "../../api/call"
import {startCall,startCallBack} from "../../api/twilio"
import pagination from "@/components/pagination.vue";

export default {
  components: {
    pagination,
  },
  data() {
    return {
      tableName: "twilioCallInfo",
      pager: {
        pageSize: 50,
        currentPage: 1,
        totalPage: 0,
      },
      selectform: {
        toPhone: "",
        fromPhone: ""
      },
      loading: false,
      multipleSelection: [],
      tableData: [],
      //播放录音
      audio: null,
      //导入号码
      labelPosition: 'right',
      importCallInfoVisible: false,
      importCallInfoLoading: false,
      importCallInfoForm: {
        tableName: "",
        toPhoneLine: "",
        toPhoneList: [],
        fromPhone: "",
        welcomeText: "",
        callPause: 5
      }
    };
  },
  created() {
    this.getInfo();
  },
  methods: {
    search() {
      this.getInfo();
    },
    getInfo() {
      this.loading = true;
      page(this.parameter()).then((res) => {
        this.loading = false;
        res.data.forEach((item, index) => {
          item.index = index + 1 + (this.pager.currentPage - 1) * this.pager.pageSize;
          return item;
        });
        this.tableData = res.data;
        this.pager.totalPage = res.total;
        if (res.code === -1) {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      });
    },

    // 搜索重置
    selectResetForm() {
      this.pager.currentPage = 1;
      this.selectform = {}
      this.multipleSelection = [];
      this.getInfo();
    },

    //搜索条件
    parameter() {
      return {
        current: this.pager.currentPage,
        size: this.pager.pageSize,
        dictValues: this.selectform,
        tableName: this.tableName
      };
    },

    // 搜索
    selectSubmit() {
      this.pager.currentPage = 1;
      this.getInfo();
      this.multipleSelection = [];
    },

    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("多选：", this.multipleSelection.length)
    },

    // 指定一个key标识这一行的数据
    getRowKey(row) {
      return row.id
    },

    //播放录音
    audioPlay(recordLocalUrl) {
      //在调用时如果有音频在播放，先做暂停操作，将audio置空
      if (this.audio !== null) {
        // 暂停录音
        this.audio.pause();
        this.audio = null;
      }
      //然后再new Audio创建新的音频
      this.audio = new Audio(recordLocalUrl);
      // 不循环播放
      this.audio.loop = false;
      // 播放录音     
      this.audio.play();
    },

    startCallBtn(id) {
      this.$confirm('此操作将发起外呼操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          if (id !== null){
            ids.push(id);
          }else{
            if (this.multipleSelection.length > 0) {
              this.multipleSelection.forEach((x) => {
                ids.push(x.id);
              });
            }
          }
          if (ids.length < 1) {
              this.$message({
                showClose: true,
                duration: 0,
                message: "当前没有选择需要操作的数据!",
                type: "error",
              });
              return;
            }
            startCall({
              "tableName": this.tableName,
              "fieldName": "id",
              "fieldValueList": ids
            }).then((res) => {
              this.getInfo();
              this.multipleSelection = [];
              this.$refs.multipleTable.clearSelection();
              this.$message({
                message: res.data,
                type: "success",
              });
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },

    startCallBackBtn(id) {
      this.$confirm('此操作将发起回调操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          if (id !== null){
            ids.push(id);
          }else{
            if (this.multipleSelection.length > 0) {
              this.multipleSelection.forEach((x) => {
                ids.push(x.id);
              });
            }
          }
          if (ids.length < 1) {
              this.$message({
                showClose: true,
                duration: 0,
                message: "当前没有选择需要操作的数据!",
                type: "error",
              });
              return;
            }
            startCallBack({
              "tableName": this.tableName,
              "fieldName": "id",
              "fieldValueList": ids
            }).then((res) => {
              this.getInfo();
              this.multipleSelection = [];
              this.$refs.multipleTable.clearSelection();
              this.$message({
                message: res.data,
                type: "success",
              });
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },

    //导入号码
    importCallInfoBtn(){
      if (this.importCallInfoForm.welcomeText === ""){
        this.$message({
          showClose: true,
          message: "请输入欢迎语",
          type: "error",
        });
        return;
      }
      if (this.importCallInfoForm.toPhoneLine === ""){
        this.$message({
          showClose: true,
          message: "请输入被叫号码",
          type: "error",
        });
        return;
      }
      this.importCallInfoForm.toPhoneList = this.importCallInfoForm.toPhoneLine.split("\n");
      this.importCallInfoForm.tableName = this.tableName;
      this.importCallInfoLoading = true;
      importCallInfo(this.importCallInfoForm).then((res) => {
        this.importCallInfoLoading = false;
        if (res.code === 0) {
          this.getInfo();
          this.$message({
            showClose: true,
            message: res.message,
            type: "success",
          });
          this.importCallInfoVisible = false;
          this.getInfo();
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      })
    },
    //打开配置文件
    openFileBtn(fileType){
      openFile(fileType).then((res) => {
        if (res.code === 0) {
          this.getInfo();
          this.$message({
            showClose: true,
            message: res.message,
            type: "success",
          });
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      })
    },

    //批量删除
    batchDeleteBtn() {
      let ids = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((x) => {
          ids.push(x.id);
        });
      }
      if (ids.length < 1) {
        this.$message({
          showClose: true,
          duration: 0,
          message: "当前没有选择需要删除的数据!",
          type: "error",
        });
        return;
      }
      batchDelete({
        "tableName": this.tableName,
        "fieldName": "id",
        "fieldValueList": ids
      }).then((res) => {
        this.getInfo();
        this.multipleSelection = [];
        this.$refs.multipleTable.clearSelection();
        this.$message({
          message: res.data,
          type: "success",
        });
      });
    },



  },
};
</script>
